package com.yuliang.utils.util;

import java.net.URLEncoder;
import java.util.*;

public class CreateSign {

    public static Map<String, Object> paramSort(Map<String, Object> params){
        Map<String, Object> treemap = new TreeMap<>(params);
        List<Map.Entry<String, Object>> list = new ArrayList<>(treemap.entrySet());
        Collections.sort(list, Comparator.comparing(Map.Entry::getKey));
        return treemap;
    }
    public static void main(String[]args){
        Map<String, Object> params = new HashMap<>();
        params.put("stime", System.currentTimeMillis());
        params.put("secret", "12345678");
        String result = getUrlParamsByMap(paramSort(params));
        System.out.println(result);
    }

    /**
     * 将map转换成url参数
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        try {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                sb.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
                sb.append("&");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }

}
